import json
import time
import logging
import datetime
import pandas as pd

import QUANTAXIS as QA
from QAStrategy.QAStrategy.qastockbase import QAStrategyStockBase
from QAPUBSUB.QAPUBSUB.producer import publisher, publisher_routing
from QAPUBSUB.QAPUBSUB.consumer import subscriber
from QATrader.QATRADER.trader import QA_TRADER
from QIFIAccount.QIFIAccount.QARealtimeStockSim import QIFI_StockSIM_Account
from QAStrategy.QAStrategy.classic_strategy.grid_strategy import GridTrade


def main():
    # account
    username = 'GRID_SIM_60_MIN_510300'
    password = '123456'
    # acc = QIFI_StockSIM_Account(username, password, init_cash=1e5)
    # acc.initial()
    # acc.log(acc.message)

    # current_time = datetime.datetime.now()
    # if current_time.hour >= 15:
    #     acc.settle()

    code = '159919'

    # subscribe codes
    print('start subscribe codes')
    publisher_routing(exchange='QARealtime_Market', routing_key='stock').pub(
        json.dumps({
            'topic': 'subscribe',
            'code': code
        }), routing_key='stock'
    )
    print('Subscribe code %s' % code)
    time.sleep(1)

    # strategy
    print('start execute strategy')
    today = datetime.date.today()
    last_year = datetime.date.today() + datetime.timedelta(days=-365)
    last_week = datetime.date.today() + datetime.timedelta(days=-7)
    last_month = datetime.date.today() + datetime.timedelta(days=-30)

    start = last_year.strftime('%Y-%m-%d')
    end = today.strftime('%Y-%m-%d')
    weight_pos = [1.0, 0.8, 0.5, 0.2, 0.0]
    weight_distance = [-2, -1, 1, 2]
    weight_pos = [1.0, 0.9, 0.7, 0.5, 0.3, 0.1, 0.0]
    weight_distance = [-3, -2, -1, 3, 6, 9]
    strategy = GridTrade(username=username, password=password, code=code,
                         market=QA.MARKET_TYPE.INDEX_CN, start=start, end=end,
                         min_trade_money=5000,
                         frequence=QA.FREQUENCE.SIXTY_MIN, strategy_id=username, init_cash=2e5,
                         deadband=0.1, dynamic=True, N=30, err='atr', atr_ratio=2,
                         weight_pos=weight_pos, weight_distance=weight_distance)
    strategy.plot_grid()
    strategy.run_sim()


if __name__ == "__main__":
    # try:
    #     from QUANTAXIS_RealtimeCollector.QARealtimeCollector.utils.logconf import update_log_file_config
    #     logfile = 'stock.sim.log'
    #     logging.config.dictConfig(update_log_file_config(logfile))
    # except Exception as e:
    #     print(e.__str__())
    main()